import os.path
import time
import logging

# 创建一个logger
logger = logging.getLogger(__file__)
logger.setLevel(logging.INFO)  # Log等级总开关

# 定义handler的输出格式
formatter = logging.Formatter("%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s")

# 创建一个handler，用于写入日志文件
rq = time.strftime('%Y%m%d', time.localtime(time.time()))
log_name = os.path.join(os.getcwd(), rq + '.txt')
logfile = log_name
fh = logging.FileHandler(logfile, mode='a+', encoding="utf8")
fh.setLevel(logging.DEBUG)  # 输出到file的log等级的开关
fh.setFormatter(formatter)

rq = time.strftime('%Y%m%d', time.localtime(time.time()))
error_path = os.path.join(os.getcwd(), rq + '_eror.txt')
fh_error = logging.FileHandler(error_path, mode='a+', encoding="utf8")
fh_error.setLevel(logging.ERROR)  # 输出到file的log等级的开关
fh_error.setFormatter(formatter)

ch = logging.StreamHandler()
ch.setLevel(logging.INFO)
ch.setFormatter(formatter)

logger.addHandler(fh)
logger.addHandler(fh_error)
logger.addHandler(ch)

import traceback

# 使用logger.XX来记录错误,这里的"error"可以根据所需要的级别进行修改


from sqlalchemy import create_engine

DB_URI = "postgresql://postgres:qiuwen123456@139.9.223.116/postgres"

engine = create_engine(DB_URI, echo=False)


def before_run():
    with engine.connect() as con:
        rs = con.execute('SELECT version()')
        for result in rs:
            logger.info(result)


def run():
    try:
        1 / 0
    except:

        logger.error(traceback.format_exc())


if __name__ == '__main__':
    before_run()
    run()
